import backtrader as bt
import pandas
import datetime
import paras
import autocode_torch
import LSTM
import datautil
from bt_strategy import MartingaleStrategy
from commission import ForexBroker, ForexSpreadCommissionScheme


def bct(symbol="FXUSDJPY", period=5):
    jpy_pair = "JPY" in symbol

    cerebro = bt.Cerebro(cheat_on_open = False,maxcpus=1)
    # cerebro.optstrategy(
    #     MartingaleStrategy,
    #     # min_gap=range(40,300,3),
    #     stoploss=range(20000,80000,3000),
    #     targetprofit=range(10000,200000,5000)
    # )

    broker = ForexBroker()
    cerebro.setbroker(broker)
    cerebro.broker.setcash(1000000.0)
    # comminfo = ForexSpreadCommissionScheme(spread=1, jpy_pair=jpy_pair, leverage=10.0, margin=1, mult=1.0,
    #                                        stocklike=True)
    # cerebro.broker.addcommissioninfo(comminfo)
    cerebro.broker.setcommission(commission=0.0005,commtype=bt.CommInfoBase.COMM_PERC, stocklike=True,leverage=10.0)

    cerebro.addstrategy(MartingaleStrategy)

    datapath = "data/{}_{}.csv".format(symbol, period)
    dataframe = pandas.read_csv(datapath, parse_dates=True, index_col=0)
    print(dataframe.head(2))
    print(dataframe.tail(2))
    data = bt.feeds.PandasData(dataname=dataframe, fromdate=datetime.datetime(2018, 4, 1),
                               todate=datetime.datetime(2019, 1, 23))
    cerebro.adddata(data, name="data0")

    # datapath1 = "data/{}_{}.csv".format("FXXAUUSD", period)
    # dataframe1 = pandas.read_csv(datapath1, parse_dates=True, index_col=0)
    # data1 = bt.feeds.PandasData(dataname=dataframe1, fromdate=datetime.datetime(2015, 5, 1),
    #                            todate=datetime.datetime(2015, 6, 1), )
    # cerebro.adddata(data1, name="data1")

    cerebro.addanalyzer(bt.analyzers.PyFolio, _name='pyfolio')

    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())

    results = cerebro.run()

    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

    # strat = results[0]
    # pyfoliozer = strat.analyzers.getbyname('pyfolio')
    # returns, positions, transactions, gross_lev = pyfoliozer.get_pf_items()
    # import pyfolio as pf
    # pf.create_full_tear_sheet(
    #     returns,
    #     positions=positions,
    #     transactions=transactions,
    #     round_trips=True)

    cerebro.plot()


if __name__ == "__main__":
    # autocode_torch.autocode(paras.dbname, paras.symbol, paras.qt_type)
    # LSTM.updatemodel(paras.dbname, paras.symbol, paras.qt_type)
    # datautil.getdatas(paras.dbname, paras.symbol, paras.qt_type)
    bct(paras.symbol, paras.qt_type)
